import {getTaskList, RoutePoint, TaskItem} from "@/services/task";
import {shipRouteLayerId, shipRoutePointLayerId, shipRouteSrcId, updateRouteSrc} from "common/src/utils/layer";
import {calcAzimuth, convert2DirectedPath, getCurrentShipInfo} from "common/src/utils/routeCalc";
import {ElMessage} from "element-plus";
import {defineStore} from "pinia";
import {useWeatherStore} from "./weather";
import {Marker} from "mapbox-gl";
import {getActiveShipMarker, getParkMarker} from 'common/src/utils/ship';
import {useTimeRangeStore} from "common/src/store/timeRange";
import {routeColors} from "common/src/utils/special";
import {getAngleText, getWindSpeed} from "common/src/utils/weather";
import {useUserStore} from "@/store";


const hiddenTasksStorageKey = 'hide-task-storage-key';

const getHiddenTasksStorage = () => {
    const raw = localStorage.getItem(hiddenTasksStorageKey);
    if (!raw) return [] as number[];
    const arr = raw
        .split(',')
        .map(s => s.trim())
        .filter(s => s !== '')
        .map(s => Number(s))
        .filter(n => Number.isFinite(n));
    // 去重
    return Array.from(new Set(arr));
};

const setHiddenTasksStorage = (finalList: number[]) => {
    // 写入“最终值”
    const next = Array.from(new Set(finalList.filter(n => Number.isFinite(n)))).sort((a, b) => a - b);
    localStorage.setItem(hiddenTasksStorageKey, next.join(','));
};

const hiddenTasksStorageKeyV2 = 'hide-task-storage-v2';

// 统一跨 taskPhase 管理：使用全局 Map 存储隐藏任务
const getHiddenTasksMap = (): Record<number, true> => {
    // 优先读 v2 JSON
    const rawV2 = localStorage.getItem(hiddenTasksStorageKeyV2);
    if (rawV2) {
        try {
            const obj = JSON.parse(rawV2) as Record<string, boolean>;
            const map: Record<number, true> = {};
            Object.keys(obj || {}).forEach(k => {
                const n = Number(k);
                if (Number.isFinite(n) && obj[k]) map[n] = true as const;
            });
            return map;
        } catch {
        }
    }
    // 兼容旧版（逗号分隔数组），迁移到 v2
    const legacy = getHiddenTasksStorage();
    const map: Record<number, true> = {};
    legacy.forEach(id => {
        if (Number.isFinite(id)) map[id] = true as const;
    });
    // 写回 v2
    localStorage.setItem(hiddenTasksStorageKeyV2, JSON.stringify(map));
    return map;
};

const setHiddenTasksMap = (map: Record<number, true>) => {
    // 只存 v2；不再写旧版，避免双写
    localStorage.setItem(hiddenTasksStorageKeyV2, JSON.stringify(map));
};

// 基于当前任务列表，投影全局隐藏 Map → 本页 hideTasks 数组
const projectHiddenToList = (list: TaskItem[], hiddenMap: Record<number, true>): number[] => {
    const ids = list.map(t => t.id);
    return ids.filter(id => !!hiddenMap[id]);
};

export const judgeItemStatus = (item: TaskItem) => {
    return true;
};

export interface RoutePointInfo {
    show: boolean;
    /** 跟踪航线对应任务的id */
    taskId: number;
    /** 跟踪航线对应的类型 */
    type: number;
    lat: number;
    lon: number;
    latLng: string;
    sog?: number;
    cog?: number;
    time: string;
    roll?: number;
    pitch?: number;
    windAngle?: number;
    windSpd?: number;
    wave?: number;
    windText: string;
}

interface TaskState {
    list: TaskItem[];
    loading: boolean;
    lastCompletedNum: number;
    markerMap: Record<number, {
        /** 起终点及中间点的marker */
        point: Marker[];
        /** 跟路线相关的 */
        route: Record<number, {
            /** 路线上船位的marker */
            ship: Marker;
        }>;
    }>;
    /** 船位marker添加点击监听函数状态 */
    shipMarkerClickFn: (taskId: number, type: number) => void;
    /** 隐藏的任务id数组 */
    hideTasks: number[];
    /** 路径点Marker */
    routePointMarker: Marker | null;
    /** 路径点Marker信息 */
    routePointInfo: RoutePointInfo;
    /** 碍航区或者危险报文信息 */
    regionWxMsgInfo: {
        info: string;
    };
    /** 顶部信息显示控制 */
    infoShow: {
        /** 路径点信息 */
        routePoint: boolean;
        /** 碍航区或者危险报文信息 */
        regionWxMsg: boolean;
        /** 姿态点查 */
        attitudeDecoder: boolean;
        /** 气象点查 */
        pointDecoder: boolean;
        /** 区划点查 */
        climaticDecoder: boolean;
    };
    /** 风浪标记数组 */
    windWaveMarkers: { marker: Marker; taskId: number; type: number }[];
    activeCardKeys: Set<number>;
    // 新增: 任务阶段和航线着色对象
    activeTaskStage: number | null;
    activeLineColorObj: any;
    /** 当前进入的任务详情id，null 表示不在详情 */
    currentTaskId: number | null;
}

// 小工具：把 Set 转回数组（避免 TS 对 this.activeCardKeys 的直接遍历报错）
function stateToArray<T>(s: Set<T>): T[] {
    const arr: T[] = []
    s.forEach(v => arr.push(v))
    return arr
}

export const useTaskStore = defineStore('task', {
    state: (): TaskState => ({
        list: [],
        loading: false,
        lastCompletedNum: 0,
        markerMap: {},
        shipMarkerClickFn: (taskId: number, type: number) => {
        },
        hideTasks: [],
        windWaveMarkers: [],
        activeCardKeys: new Set<number>() as Set<number>,
        routePointMarker: null,
        routePointInfo: {
            show: false,
            taskId: -1,
            type: 0,
            lat: 0,
            lon: 0,
            latLng: '',
            time: '',
            windText: '',
        },
        regionWxMsgInfo: {
            info: '',
        },
        infoShow: {
            routePoint: false,
            regionWxMsg: false,
            attitudeDecoder: false,
            pointDecoder: false,
            climaticDecoder: false,
        },
        activeTaskStage: null,
        activeLineColorObj: null,
        currentTaskId: null,
    }),
    getters: {
        isCardActive: (state) => (key: number) => state.activeCardKeys.has(key),
    },
    actions: {
        async getList() {
            const userStore = useUserStore();
            this.loading = true;
            const param = {
                page: 1,
                length: 100,
                taskType: 0
            }
            if (userStore.taskPhase) {
                param.taskType = userStore.taskPhase;
            } else {
                delete param.taskType;
            }
            try {
                const res = await getTaskList(param);
                this.list = res.list;
                // 基于全局隐藏 Map 投影本期列表
                const hiddenMap = getHiddenTasksMap();
                this.hideTasks = projectHiddenToList(this.list, hiddenMap);
                const completeNum = res.list.reduce((prev, item) => {
                    const status = judgeItemStatus(item);
                    if (status) {
                        return prev + 1;
                    }
                    return prev;
                }, 0);
                if (completeNum < this.list.length) {
                    setTimeout(() => {
                        this.getList();
                    }, 1000);
                }
                if (completeNum > this.lastCompletedNum) {
                    this.updateRouteLayer();
                }
            } catch (err) {
                console.log(err);
                ElMessage({
                    type: 'warning',
                    message: '获取任务列表失败, 请刷新页面重试',
                });
            } finally {
                this.loading = false;
            }
        },
        updateShipMarker(shipMarker: Marker, route: RoutePoint[]) {
            const timeRangeStore = useTimeRangeStore();
            const location = getCurrentShipInfo(route.map((point, idx) => {
                const {lat, lon, ts: time, cog} = point;
                // let cog: number = 0;
                // if (idx < route.length - 1) {
                //   const nextPoint = route[idx + 1];
                //   cog = calcAzimuth(lon, lat, nextPoint.lon, nextPoint.lat, true);
                // }
                // console.log(srcCog, cog);
                const pts = time * 1000;
                return {lon, lat, cog, sailingTs: pts, pts, isGC: false};
            }), timeRangeStore.currentTime);
            (shipMarker.getElement().children[0] as HTMLElement).style.transform = `rotate(${location.cog}deg)`;
            const [lon, lat] = location.center;
            shipMarker.setLngLat([lon, lat]);
        },
        updateAllShipMarker() {
            this.list.forEach((task) => {
                task.routeType.forEach((type) => {
                    if (task.routes?.[type]?.length) {
                        const shipMarker = this.markerMap[task.id]?.route?.[type]?.ship;
                        if (shipMarker) {
                            this.updateShipMarker(shipMarker, task.routes[type]);
                        }
                    }
                });
            });
        },
        updateRouteLayer() {
            this.setActiveTaskStage(null)
            this.setActiveLineColorObj(null)
            const geoJson: GeoJSON.FeatureCollection<GeoJSON.Geometry> = {
                type: 'FeatureCollection',
                features: []
            };
            const pointGeoJson: GeoJSON.FeatureCollection<GeoJSON.Geometry> = {
                type: 'FeatureCollection',
                features: [],
            };
            const weatherStore = useWeatherStore();
            this.list.forEach((task) => {
                if (this.markerMap[task.id]) {
                    this.markerMap[task.id].point.forEach((marker) => marker.remove());
                    Object.entries(this.markerMap[task.id].route).forEach(([key, value]) => {
                        if (value.ship) {
                            value.ship.remove();
                        }
                    });
                }
                this.markerMap[task.id] = {point: [], route: {}};
                let showTask = !this.hideTasks.includes(task.id);
                const userStore = useUserStore();
                if (task.taskStage !== userStore.taskPhase) showTask = false
                if (task.routeType.some(type => task.routes?.[type]?.length)) {
                    // 关键点marker
                    task.points.forEach((point, idx) => {
                        let name = '经';
                        let index = idx;
                        if (idx === 0) {
                            name = '起';
                            index = 0;
                        } else if (idx === task.points.length - 1) {
                            name = '终';
                            index = 0;
                        }
                        const marker = getParkMarker(name, index);
                        const {latitude, longitude} = point;
                        marker.setLngLat([longitude, latitude]);
                        if (showTask) {
                            marker.addTo(weatherStore.map as any);
                        }
                        this.markerMap[task.id].point.push(marker);
                    });
                }
                task.routeType.forEach((type) => {
                    if (task.routes?.[type]?.length) {
                        const route = task.routes[type];
                        const shipMarker = getActiveShipMarker(task.mmsi, () => this.shipMarkerClickFn(task.id, type), routeColors[type]);
                        this.markerMap[task.id].route[type] = {ship: shipMarker};
                        this.updateShipMarker(shipMarker, route);
                        if (showTask) {
                            shipMarker.addTo(weatherStore.map as any);
                        }
                        geoJson.features.push({
                            type: 'Feature',
                            properties: {
                                id: task.id,
                                type,
                                color: routeColors[type] || routeColors[0],
                                'border-color': routeColors[type] || routeColors[0],
                            },
                            geometry: {
                                type: 'LineString',
                                coordinates: convert2DirectedPath(route.map((point) => {
                                    return [point.lon, point.lat];
                                })),
                            },
                        });
                        if (showTask) {
                            route.forEach((point) => {
                                pointGeoJson.features.push({
                                    type: 'Feature',
                                    properties: {
                                        id: task.id,
                                        type,
                                        ...point,
                                    },
                                    geometry: {
                                        type: 'Point',
                                        coordinates: [point.lon, point.lat],
                                    }
                                });
                            });
                        }
                    }
                });
            });
            this.updateTaskListDisplay();
            updateRouteSrc(weatherStore.map as any, geoJson, pointGeoJson);
        },

        setActiveTaskStage(stage: number | null) {
            this.activeTaskStage = stage;
        },
        setActiveLineColorObj(obj: any) {
            this.activeLineColorObj = obj;
        },

        toggleCardKey(key: number) {
            // 重新赋值一个新 Set 以确保响应式更新
            const s = new Set(stateToArray(this.activeCardKeys))
            if (s.has(key)) s.delete(key)
            else s.add(key)
            this.activeCardKeys = s
            /** 航线红黄绿分色-红绿灯（使用 store 中的激活阶段与分色对象） */
            if (!this.activeLineColorObj) return
            this.updateRouteColorByThreshold(this.activeLineColorObj);
        },
        clearCardKeys() {
            this.activeCardKeys = new Set()
        },
        setCardKeys(keys: Iterable<number>) {
            this.activeCardKeys = new Set(keys)
        },

        /**
         * 根据风速和浪高阈值，分段着色指定任务的航线-红绿灯（只对选中的 type 生效）
         */
        updateRouteColorByThreshold(config: {
            id: number;
            alertWaveHeight: number;
            alertWindSpeed: number;
            routes: Record<number, { lon: number; lat: number; windSpeed: number; waveHeight: number }[]>;
        }) {
            if (this.activeTaskStage === 1) return;
            const {id, alertWaveHeight, alertWindSpeed, routes} = config;
            const weatherStore = useWeatherStore();
            const map = weatherStore.map as any;

            const allTypes = Object.keys(routes).map(k => Number(k));
            const selectedTypes = new Set<number>(this.activeCardKeys);   // 多选集合
            const hasSelection = selectedTypes.size > 0;

            // —— 构建“原色整段”要素
            const buildOriginalFeatures = (types: number[]) => {
                const features: GeoJSON.Feature<GeoJSON.LineString>[] = [];
                types.forEach(type => {
                    const ptsArr = routes[type] || [];
                    if (!ptsArr.length) return;
                    const raw = ptsArr.map(p => [p.lon, p.lat] as [number, number]);
                    const coords = convert2DirectedPath(raw);
                    if (coords.length < 2) return;
                    features.push({
                        type: 'Feature',
                        properties: {
                            id,
                            type,
                            color: routeColors[type] || routeColors[0],
                            'border-color': routeColors[type] || routeColors[0],
                        },
                        geometry: {type: 'LineString', coordinates: coords},
                    });
                });
                return features;
            };

            // —— 构建“阈值分段”要素（红/黄/绿）
            const buildSegmentFeatures = (types: number[]) => {
                const features: GeoJSON.Feature<GeoJSON.LineString>[] = [];
                types.forEach(type => {
                    const ptsArr = routes[type] || [];
                    if (ptsArr.length < 2) return;
                    const raw = ptsArr.map(p => [p.lon, p.lat] as [number, number]);
                    const coords = convert2DirectedPath(raw);
                    for (let i = 1; i < coords.length; i++) {
                        const curr = ptsArr[i];
                        let color = '#00ff00'; // 绿
                        if (curr.windSpeed > alertWindSpeed || curr.waveHeight > alertWaveHeight) {
                            color = '#ff0000';   // 红
                        } else if (
                            curr.windSpeed > alertWindSpeed * 0.7 ||
                            curr.waveHeight > alertWaveHeight * 0.7
                        ) {
                            color = '#fff300';   // 黄
                        }
                        features.push({
                            type: 'Feature',
                            properties: {
                                id,
                                type,
                                color,
                                'border-color': routeColors[type] || routeColors[0],
                            },
                            geometry: {type: 'LineString', coordinates: [coords[i - 1], coords[i]]},
                        });
                    }
                });
                return features;
            };

            const source = map.getSource(shipRouteSrcId) as mapboxgl.GeoJSONSource;
            if (!source) return;

            const data = (source as any)._data as GeoJSON.FeatureCollection<GeoJSON.Geometry>;

            // 有选中：选中的 type 用分段色，未选中的用原色；无选中：全部原色
            const typesSeg = hasSelection ? allTypes.filter(t => selectedTypes.has(t)) : [];
            const typesOri = hasSelection ? allTypes.filter(t => !selectedTypes.has(t)) : allTypes;

            // 先移除当前任务中将被替换的这些 type 的旧要素
            const typesToReplace = new Set<number>([...typesSeg, ...typesOri]);
            const otherFeatures = data.features.filter(f => {
                const p = f.properties as any;
                return !(p && p.id === id && typesToReplace.has(p.type));
            });

            const merged: GeoJSON.FeatureCollection<GeoJSON.Geometry> = {
                type: 'FeatureCollection',
                features: [
                    ...otherFeatures,
                    ...buildOriginalFeatures(typesOri),
                    ...buildSegmentFeatures(typesSeg),
                ],
            };

            source.setData(merged);
            // ——— 选中若干条时：未被选中的（仅限当前任务 id）在原有色基础上整体变暗；若一个都没选，则保持不变
            try {
                const selectedArr = Array.from(selectedTypes);
                // 当无任何选择时，直接还原为 1，避免 match 分支列表为空导致的校验错误
                if (!hasSelection) {
                    map.setPaintProperty(shipRouteLayerId, 'line-opacity', 1);
                } else {
                    map.setPaintProperty(
                        shipRouteLayerId,
                        'line-opacity',
                        [
                            'case',
                            [
                                'all',
                                ['==', ['get', 'id'], id],
                                ['!', ['match', ['get', 'type'], selectedArr, true, false]]
                            ],
                            0.4,
                            1
                        ]
                    );
                }
            } catch (e) {
                console.warn('set line-opacity failed:', e);
            }
        },
        /**
         * 在指定任务航线上添加风向标和波向标
         */
        addRouteWindWaveMarkers(config: {
            id: number;
            routes: Record<number, {
                lon: number;
                lat: number;
                windDegree: number;
                windKnots: number;
                seaWaveDegree: number;
            }[]>;
        }) {
            const {id, routes} = config;
            const weatherStore = useWeatherStore();
            const map = weatherStore.map as any;

            // ✅ 先清理：本次将要更新的类型集合
            const typesToUpdate = new Set(Object.keys(routes).map(k => Number(k)));
            this.windWaveMarkers = this.windWaveMarkers.filter(entry => {
                const shouldRemove = entry.taskId === id && typesToUpdate.has(entry.type);
                if (shouldRemove) entry.marker.remove();
                return !shouldRemove;
            });

            Object.entries(routes).forEach(([typeKey, ptsArr]) => {
                const type = Number(typeKey);
                ptsArr.forEach((pt, idx) => {
                    // 点位抽稀3抽1
                    if (idx !== 0 && idx !== ptsArr.length - 1 && idx % 3 !== 0) {
                        return;
                    }
                    const {lon, lat, windDegree, windKnots, seaWaveDegree} = pt;
                    // 计算贝福特风级档位
                    const _bf = getWindSpeed(windKnots / 5);
                    const bf = lat > 0 ? (_bf === 0 ? 0 : _bf + 16) : _bf;
                    const svgId = `icon-wind${bf}`;

                    // 创建风向标
                    const windEl = document.createElement('div');
                    windEl.className = 'windMarker';
                    windEl.style.width = '32px';
                    windEl.style.height = '32px';
                    windEl.style.top = '-16px';
                    windEl.innerHTML = `<svg><use xlink:href="#${svgId}"/></svg>`;
                    const windSvg = windEl.firstChild as HTMLElement;
                    windSvg.style.width = '32px';
                    windSvg.style.height = '32px';
                    windSvg.style.transform = `rotate(${windDegree}deg)`;
                    windSvg.style.transformOrigin = 'center bottom';
                    const windMarker = new Marker(windEl)
                        .setLngLat([lon, lat])
                        .addTo(map);
                    this.windWaveMarkers.push({marker: windMarker, taskId: id, type});

                    // 创建浪向标
                    const waveEl = document.createElement('div');
                    waveEl.className = 'waveMaker';
                    waveEl.style.width = '24px';
                    waveEl.style.height = '24px';
                    waveEl.style.top = '-12px';
                    waveEl.innerHTML = `<svg><use xlink:href="#icon-swell-cog"/></svg>`;
                    const waveSvg = waveEl.firstChild as HTMLElement;
                    waveSvg.style.width = '24px';
                    waveSvg.style.height = '24px';
                    waveSvg.style.transform = `rotate(${(seaWaveDegree + 180) % 360}deg)`;
                    waveSvg.style.transformOrigin = 'center bottom';
                    const waveMarker = new Marker(waveEl)
                        .setLngLat([lon, lat])
                        .addTo(map);
                    this.windWaveMarkers.push({marker: waveMarker, taskId: id, type});
                });
            });
        },

        /**
         * 移除所有风向标和波向标
         */
        removeRouteWindWaveMarkers() {
            this.windWaveMarkers.forEach(entry => entry.marker.remove());
            this.windWaveMarkers = [];
        },
        showTaskRoutePoint(id?: number) {
            const weatherStore = useWeatherStore();
            weatherStore.map?.setFilter(shipRoutePointLayerId, [
                'case',
                ['has', 'id'], ['in', ['get', 'id'], ['literal', id !== undefined ? [id] : []]],
                false
            ]);
            if (id && this.hideTasks.includes(id)) {
                const hiddenMap = getHiddenTasksMap();
                delete hiddenMap[id];
                setHiddenTasksMap(hiddenMap);
                this.hideTasks = projectHiddenToList(this.list, hiddenMap);
                this.updateTaskListDisplay();
            }
        },
        updateTaskListDisplay() {
            const weatherStore = useWeatherStore();
            if (!weatherStore.map) {
                return;
            }
            const showTask: number[] = [];
            const userStore = useUserStore();
            this.list.forEach(task => {
                const {id, routeType, taskStage} = task;
                if (this.hideTasks.includes(id) || (userStore.taskPhase ? taskStage !== userStore.taskPhase : false)) {
                    this.markerMap[id].point.forEach(marker => marker.remove());
                    routeType.forEach(type => {
                        this.markerMap[id].route[type]?.ship?.remove();
                    });
                } else {
                    showTask.push(id);
                    this.markerMap[id].point.forEach(marker => marker.addTo(weatherStore.map as any));
                    routeType.forEach(type => {
                        this.markerMap[id].route[type]?.ship?.addTo(weatherStore.map as any);
                    });
                }
            });
            weatherStore.map.setFilter(shipRouteLayerId, [
                'case',
                ['has', 'id'], ['in', ['get', 'id'], ['literal', [...showTask]]],
                false
            ]);
            weatherStore.map.setFilter(
                shipRoutePointLayerId,
                ['in', ['get', 'id'], ['literal', showTask]]
            );
        },
        toggleTaskVisible(id: number) {
            const hiddenMap = getHiddenTasksMap();
            if (hiddenMap[id]) delete hiddenMap[id];
            else hiddenMap[id] = true as const;
            setHiddenTasksMap(hiddenMap);
            this.hideTasks = projectHiddenToList(this.list, hiddenMap);
            this.updateTaskListDisplay();
        },
        /**
         * 切换所有任务航线和标记的显示状态
         */
        toggleAllTasksVisible(show: boolean) {
            const hiddenMap = getHiddenTasksMap();
            const currentIds = this.list.map(task => task.id);
            if (show) {
                // 显示当前列表所有：从全局隐藏 Map 中移除本期所有 id
                currentIds.forEach(id => {
                    if (hiddenMap[id]) delete hiddenMap[id];
                });
            } else {
                // 隐藏当前列表所有：把本期所有 id 加入全局隐藏 Map
                currentIds.forEach(id => {
                    hiddenMap[id] = true as const;
                });
            }
            setHiddenTasksMap(hiddenMap);
            this.hideTasks = projectHiddenToList(this.list, hiddenMap);
            this.updateTaskListDisplay();
        },
        focusOnTask(id: number) {
            const hiddenMap = getHiddenTasksMap();
            // 仅确保被聚焦的任务显示，不更改其他任务的显隐
            if (hiddenMap[id]) {
                delete hiddenMap[id];
                setHiddenTasksMap(hiddenMap);
                this.hideTasks = projectHiddenToList(this.list, hiddenMap);
            }
            this.updateTaskListDisplay();
        },
        updateRoutePointInfo(info: Partial<RoutePointInfo>) {
            if (this.infoShow.regionWxMsg) {
                this.infoShow.regionWxMsg = false;
            }
            let windText = '--';
            const {windSpd, windAngle} = info;
            if (windSpd) {
                const angleText = (windAngle || (windAngle === 0)) ? getAngleText(windAngle) : '--';
                windText = `${angleText} ${windSpd.toFixed(2)}kts ${windAngle?.toFixed(0)}°`
            }
            Object.assign(this.routePointInfo, {...info, windText});
        },
        updateRoutePointMarker(lon: number, lat: number) {
            this.routePointMarker?.setLngLat([lon, lat]);
            if (!this.infoShow.routePoint) {
                const weatherStore = useWeatherStore();
                Object.assign(this.infoShow, {
                    routePoint: true,
                    regionWxMsg: false,
                    attitudeDecoder: false,
                    pointDecoder: false,
                });
                this.routePointMarker?.addTo(weatherStore.map as any);
            }
        },
        removeRoutePointMarker() {
            this.routePointMarker?.remove();
            this.infoShow.routePoint = false;
            this.routePointInfo.taskId = -1;
        },
        updateRegionWxMsgInfo(info: string) {
            if (this.infoShow.routePoint) {
                this.infoShow.routePoint = false;
            }
            this.regionWxMsgInfo.info = info;
            this.removeRoutePointMarker();
            Object.assign(this.infoShow, {
                routePoint: false,
                regionWxMsg: true,
                attitudeDecoder: false,
                pointDecoder: false,
                climaticDecoder: false,
            });
        },
        showPointDecoderInfo() {
            this.removeRoutePointMarker();
            Object.assign(this.infoShow, {
                routePoint: false,
                regionWxMsg: false,
                attitudeDecoder: false,
                pointDecoder: true,
                climaticDecoder: false,
            });
        },
        showAttitudeDecoderInfo() {
            this.removeRoutePointMarker();
            Object.assign(this.infoShow, {
                routePoint: false,
                regionWxMsg: false,
                attitudeDecoder: true,
                pointDecoder: false,
                climaticDecoder: false,
            });
        },
        showClimaticDecoderInfo() {
            this.removeRoutePointMarker();
            Object.assign(this.infoShow, {
                routePoint: false,
                regionWxMsg: false,
                attitudeDecoder: false,
                pointDecoder: false,
                climaticDecoder: true,
            });
        },
        setCurrentTask(id: number | null) {
            this.currentTaskId = id;
        },
        // 更新url
        replaceUrlDir(url: string) {
            let str = url
            if (this.currentTaskId) {
                str = str.replace('{dataDir}', `task/`)
                str = str.replace('{taskId}', `${this.currentTaskId}/pic/ec/`)
            }else {
                str = str.replace('{dataDir}', `packForecast/`)
                str = str.replace('{taskId}', '')
            }
            return str;
        },
    },
});
